use crate::controls::control_utils::{add_to_svchost_group, set_service_dll_path, show_messagebox};
use crate::globals::constants::*;
use crate::internal::utils::*;
use std::ffi::OsString;
use std::path::PathBuf;
use winapi::shared::minwindef::DWORD;
use windows::Win32::UI::WindowsAndMessaging::{MB_ICONINFORMATION, MB_ICONWARNING};
use windows_service::Result;
use windows_service::service::{
    ServiceAccess, ServiceErrorControl, ServiceInfo, ServiceStartType, ServiceType,
};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

/// 安装服务
pub fn install_service() -> Result<()> {
    show_messagebox("安装服务", "即将安装服务，请稍候...", MB_ICONINFORMATION);

    // 连接到服务管理器
    let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
    let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;

    // 检查服务是否已存在
    match service_manager.open_service(SERVICE_NAME, ServiceAccess::QUERY_STATUS) {
        Ok(_) => {
            // 服务已存在，显示提示并返回
            show_messagebox(
                "安装服务 - 提示",
                &format!("服务 {} 已经存在！请先卸载后再安装。", SERVICE_NAME),
                MB_ICONWARNING,
            );
            return Ok(());
        }
        Err(windows_service::Error::Winapi(e)) if e.raw_os_error() == Some(1060) => {
            // ERROR_SERVICE_DOES_NOT_EXIST，继续安装
        }
        Err(e) => {
            // 其他错误
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "安装服务 - 错误",
                &format!("检查服务时发生错误！错误代码: {}", error_code),
                MB_ICONWARNING,
            );
            return Err(e);
        }
    }

    // 获取svchost路径
    let system32_dir = get_system32_directory()
        .ok_or_else(|| windows_service::Error::Winapi(std::io::Error::last_os_error()))?;

    let svchost_path = format!("{system32_dir}\\svchost.exe");

    // 定义服务信息
    let service_info = ServiceInfo {
        name: OsString::from(SERVICE_NAME),
        display_name: OsString::from(DISPLAY_NAME),
        service_type: ServiceType::SHARE_PROCESS,
        start_type: ServiceStartType::AutoStart,
        error_control: ServiceErrorControl::Normal,
        executable_path: PathBuf::from(svchost_path),
        launch_arguments: vec![OsString::from("-k"), OsString::from(SERVICE_GROUP)],
        dependencies: vec![],
        account_name: None, // 以System账户运行
        account_password: None,
    };

    // 创建服务
    let service = service_manager.create_service(
        &service_info,
        ServiceAccess::CHANGE_CONFIG | ServiceAccess::START,
    )?;

    // 设置服务描述
    service.set_description(DESCRIPTION)?;

    // 设置服务DLL路径 (这部分仍需要使用原有代码，因为windows-service库不直接支持设置ServiceDll)
    let dll_result = set_service_dll_path(SERVICE_NAME);
    if let Err(error) = dll_result {
        return Err(windows_service::Error::Winapi(
            std::io::Error::from_raw_os_error(error as i32),
        ));
    }

    // 添加到svchost组 (同样需要保留原有代码)
    let group_result = add_to_svchost_group();
    if let Err(error) = group_result {
        return Err(windows_service::Error::Winapi(
            std::io::Error::from_raw_os_error(error as i32),
        ));
    }

    // 启动服务
    match service.start::<&str>(&[]) {
        Ok(_) => {
            // 服务启动成功
            show_install_result_message(true, None);
        }
        Err(e) => {
            // 服务启动失败，但安装成功
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "启动服务 - 警告",
                &format!("服务安装成功，但启动失败！错误代码: {}", error_code),
                MB_ICONWARNING,
            );
            // 仍然返回安装成功的消息
            show_install_result_message(true, None);
        }
    }

    Ok(())
}

// 显示结果消息框
fn show_install_result_message(success: bool, error_code: Option<DWORD>) {
    let (message, title) = if success {
        (
            format!(
                "服务 {} 安装成功！\n显示名称: {}\n描述: {}",
                SERVICE_NAME, DISPLAY_NAME, DESCRIPTION
            ),
            "安装服务 - 成功".to_string(),
        )
    } else {
        (
            format!(
                "服务 {} 安装失败！错误代码: {}",
                SERVICE_NAME,
                error_code.unwrap_or(0)
            ),
            "安装服务 - 失败".to_string(),
        )
    };

    show_messagebox(
        &title,
        &message,
        if success {
            windows::Win32::UI::WindowsAndMessaging::MB_ICONINFORMATION
        } else {
            windows::Win32::UI::WindowsAndMessaging::MB_ICONERROR
        },
    );
}
